<template>
  <div style="height: 80vh;">
    <VFormDesigner ref="designerRef" />
    <div style="text-align:right;margin-top:16px;">
      <el-button @click="goBack">返回</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getFormDetail, editForm } from '@/api/workflow/form.api'
import { ElMessage } from 'element-plus'
import { VFormDesigner } from 'vform3-builds'

// 引入VForm3设计器样式
import 'vform3-builds/dist/designer.style.css'

const route = useRoute()
const router = useRouter()
const designerRef = ref()
const formId = route.query.id

onMounted(async () => {
  if (formId) {
    const res = await getFormDetail(formId)
    let schema = res.formSchema || res.form_schema || res.schema
    let parsed = {}
    if (typeof schema === 'string' && schema.trim() !== '') {
      try {
        parsed = JSON.parse(schema)
      } catch (e) {
        parsed = {}
      }
    } else if (typeof schema === 'object' && schema !== null) {
      parsed = schema
    }
    if (!parsed.widgetList) parsed.widgetList = []
    if (!parsed.formConfig) parsed.formConfig = {}
    await nextTick()
    if (designerRef.value && typeof designerRef.value.setFormJson === 'function') {
      designerRef.value.setFormJson(parsed)
    }
  }
})

async function onSave() {
  let latestSchema = designerRef.value?.getFormJson?.() || {}
  const payload = { ...route.query, formSchema: JSON.stringify(latestSchema) }
  await editForm(payload)
  ElMessage.success('表单设计已保存')
}
function goBack() {
  router.back()
}
</script>
